//
//  PerfectInfoViewController.m
//  work
//
//  Created by 徐宏飞 on 16/5/24.
//  Copyright © 2016年 方伟. All rights reserved.
//

#import "PerfectInfoViewController.h"
#import "TZImagePickerController.h"

//#import "UIImage+UIImage_Tool.h"
#import "UpYun.h"

@interface PerfectInfoViewController ()<UIPickerViewDelegate,
UIPickerViewDataSource,
TZImagePickerControllerDelegate,
imageUploadToolDelegate,
NetworkToolerDelegate,
UITextFieldDelegate
>

@property (weak, nonatomic) IBOutlet UITextField *tfdWorkerName;    //姓名
@property (weak, nonatomic) IBOutlet UITextField *tfdIDnumber;      //身份证号码
@property (weak, nonatomic) IBOutlet UITextField *tfdPrice;         //人工单价


@property (nonatomic, strong) UILabel *lblWorkerName;   //姓名
@property (nonatomic, strong) UILabel *lblProfession;   //工种
@property (nonatomic, strong) UILabel *lblPrice;        //价格
@property (nonatomic, strong) UILabel *lblIDnumber;     //身份证号
@property (nonatomic, strong) UILabel *lblStartTime;    //工龄



@property (weak, nonatomic) IBOutlet UIButton *btnIcon;
@property (weak, nonatomic) IBOutlet UIButton *btnIDnumber;

@property (weak, nonatomic) IBOutlet UIButton *workType;
@property (weak, nonatomic) IBOutlet UIButton *startTime;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutHeight;

@property (weak, nonatomic) IBOutlet UIView *baseView;
@property (nonatomic, strong) UITapGestureRecognizer *tap;

@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) UIPickerView *pickview;
@property (nonatomic, strong) NSArray *workArray;//工种数据源
@property (nonatomic, strong) NSMutableArray *startTimeArray;//工种数据源

@property (nonatomic, assign) int type;  //时间和工人的区分
@property (nonatomic, assign) int iconType;  //touxiang


@property (nonatomic, strong)NSMutableArray *selectedPhotos;
@property (nonatomic, strong)NSMutableArray *selectedAssets;

@property (nonatomic ,strong)UIImage *iconImage;
@property (nonatomic ,strong)UIImage *idCardImage;



@property (nonatomic, assign)BOOL isSelectOriginalPhoto;
@property (nonatomic, strong) NSMutableArray *imageUpArray;
@property (nonatomic, copy) NSString *workTapy;  //touxiang

//@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, assign) BOOL picIsfinishPick;   //判断是否成功选择图片
@property (nonatomic, assign) BOOL change;   //判断是否需要上传图片
@property (nonatomic ,strong)imageUploadTool *imageuploadtool;

@property (nonatomic, strong) ZhuangxiuManager *manager;
@property (nonatomic, strong) TZImageManager   *managers;





@end

@implementation PerfectInfoViewController


#pragma mark - life cycle

- (void)initNavigationBar
{
    self.enableReturnButton = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _manager = [ZhuangxiuManager shareManager];

    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = UIColorFromRGB(0xFAFAFA);
    self.title = @"个人信息完善";
    _imageUpArray = [[NSMutableArray alloc]init];
//    _imageArray = [[NSMutableArray alloc]init];

    
    _workArray = @[@"工种类型",@"设计师",@"水电工",@"泥工",@"木工",@"油漆工"];
    _startTimeArray = [NSMutableArray array];
    for (int i = 1; i <= 30; i++) {
        [_startTimeArray addObject:[NSString stringWithFormat:@"%d", i]];
    }

    
    self.tfdWorkerName.leftView = self.lblWorkerName;
    self.tfdWorkerName.leftViewMode = UITextFieldViewModeAlways;
    
    self.tfdIDnumber.leftView = self.lblIDnumber;
    self.tfdIDnumber.leftViewMode = UITextFieldViewModeAlways;
    
    self.tfdPrice.leftView  = self.lblPrice;
    self.tfdPrice.leftViewMode = UITextFieldViewModeAlways;
    
    
    
    [_baseView addGestureRecognizer:self.tap];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //6p
    if (SCREEN_HEIGHT == 736) {
        _layoutHeight.constant = 120;
    }
    //5s
    if (SCREEN_HEIGHT == 568 || SCREEN_HEIGHT == 480) {
        _layoutHeight.constant = 90;
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}




#pragma mark - data

-(void)_sendVerifyRequest{
    

    NSDictionary *parameters = @{
                                 
                                 @"session_id":_manager.sessionid,
                                 @"avatar":_imageUpArray[0],
                                 @"pic_idcard":_imageUpArray[1],
                                 @"real_name": _tfdWorkerName.text,
                                 @"work_year": _startTime.titleLabel.text,
                                 @"type_id":_workTapy,
                                 @"idcard": _tfdIDnumber.text,
                                 @"price" : _tfdPrice.text
                                 };
    
    
    NSLog(@"%@", parameters);
    
    NetworkTooler *networkTool = [NetworkTooler new];
    networkTool.delegate = self;
   [networkTool parameters:parameters withURL:sendVerifyRequest_show withIsPaparameters:YES];
    
}


#pragma mark - UIPickerViewDataSoure
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (_type == 0) {
        return _workArray.count;
   
    }else{
        
        return _startTimeArray.count;
    }
}
#pragma mark - UIPickerViewDelegate
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    
    if (_type == 0) {
        return [_workArray objectAtIndex:row];
        
    }else{
    
        return [_startTimeArray objectAtIndex:row];

    
    }


}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (_type == 0) {

        _workTapy = [NSString stringWithFormat:@"%ld",(long)row];
        return [_workButton setTitle:[_workArray objectAtIndex:row] forState:UIControlStateNormal];
        
    }else{
     
        return [_statTimeButton setTitle:[_startTimeArray objectAtIndex:row] forState:UIControlStateNormal];
    
    }
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel *myView = nil;
    myView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    //使用了不推荐使用的方法
   
    
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    myView.textAlignment = UITextAlignmentCenter;
    if (_type == 0) {
        
        myView.text = [_workArray objectAtIndex:row];
    }else{
        myView.text = [_startTimeArray objectAtIndex:row];

    }
    myView.font = [UIFont systemFontOfSize:14];
    myView.backgroundColor = [UIColor clearColor];
    return myView;
#pragma clan diagnostic pop
    
}





#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}





#pragma mark - imageUploadToolDelegate

- (void)returnImageURL:(NSString *)imageURL{
    
    [_imageUpArray addObject:imageURL];
   
    if (_imageUpArray.count == 2) {
        [self _sendVerifyRequest];
    }
    
}
- (void)returnError:(NSString *)error{
    [GiabHUD hideUIBlockingIndicator];


    [self actionAlert:error withCode:@"1"];
  
}


/// 用户选择好了图片，如果assets非空，则用户选择了原图。
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    _isSelectOriginalPhoto = isSelectOriginalPhoto;

    NSLog(@"%@",assets);
    //区分是否显示了原图
    if (isSelectOriginalPhoto) {
        if (!_selectedPhotos) {
            
            _selectedPhotos = [NSMutableArray new];
        }
        
        if (!_managers) {
            
            _managers = [TZImageManager new];
        }
        
        [_selectedPhotos removeAllObjects];
        
        //获取原图
            [ _managers getOriginalPhotoWithAsset:assets[0] completion:^(UIImage *photo, NSDictionary *info) {
                
            
                if (photo.size.width  >1200) {
                    
                    photo = [photo scaleToSize:photo size:CGSizeMake(1200, 80)];
                }
            
                    [_selectedPhotos addObject:photo];
                    [self endselectedPhtotos];
                
                

            }];
            
        
    }else{
    
        _selectedPhotos = [NSMutableArray  arrayWithArray:photos];
        [self endselectedPhtotos];
    
    }
    
}
#pragma mark - NetworkToolerDelegate

- (void)returnData:(id )data{

    [self actionAlert:nil withCode:@"0"];
    [GiabHUD hideUIBlockingIndicator];
  
}
- (void)returnRequestError:(NSError *)error{
    
    [GiabHUD hideUIBlockingIndicator];

    [self actionAlert:@"网络异常" withCode:@"1"];
}
- (void)returnMsg:(NSString *)Msg{
    [GiabHUD hideUIBlockingIndicator];
    

    [self actionAlert:Msg withCode:@"1"];
}


#pragma mark - event response
- (IBAction)btnTakeIconAction:(id)sender {
    //头像
    [self _pickImageWithType:0];

}



- (IBAction)btnTakeIDCardAction:(id)sender {
    //身份证照片
    [self _pickImageWithType:1];
}


- (void) _pickImageWithType:(int)iconType{
    _iconType = iconType;
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
//    imagePickerVc.selectedAssets = _selectedAssets; // optional, 可选的
    
    // 在这里设置imagePickerVc的外观
    imagePickerVc.navigationBar.barTintColor = COLOR_THEHE;
    imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    imagePickerVc.oKButtonTitleColorNormal = COLOR_THEHE;
    
    // Set allow picking video & photo & originalPhoto or not
    // 设置是否可以选择视频/图片/原图
    // imagePickerVc.allowPickingVideo = NO;
    // imagePickerVc.allowPickingImage = NO;
    // imagePickerVc.allowPickingOriginalPhoto = NO;
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}




- (IBAction)getWorker_type:(id)sender {
    
    [self.view endEditing:YES];
    //工种
    [self configurationSubView:0];
    
}

- (IBAction)getStartDate:(id)sender {
    [self.view endEditing:YES];
    //入行时间
    [self configurationSubView:1];

}



- (void)TapAction{
    [self.view endEditing:YES];
}

- (IBAction)upDataInfo:(id)sender {
    

    if (![self isCanUpData]) {
        return;
    };
    [GiabHUD showUIBlockingIndicatorWithText:@"正在申请..."];
   
   
    
    if (_imageUpArray.count == 2 && !_change) {
       
        [self _sendVerifyRequest];
    }else{
    
        
        
        if (!_imageuploadtool) {
            _imageuploadtool = [imageUploadTool new];
            
        }
        
       
        _imageuploadtool.delegate = self;
        _imageuploadtool.worker_id  = _manager.worker_id ;
        
        //上传头像
        _imageuploadtool.type = UPLOADIMAGETYPEICON;
        _imageuploadtool.selectedImage = _iconImage;
        [_imageuploadtool uplodImage];
        //上传身份证
        _imageuploadtool.type = UPLOADIMAGETYPEIDCORD;
        _imageuploadtool.selectedImage = _idCardImage;
        [_imageuploadtool uplodImage];
        
    
      
    
    }
  
}

-(void)cancelBtnClick{
    [self removeBackView];
}
-(void)okBtnClick{
    [self removeBackView];
}
-(void)removeBackView{
    [_backView removeFromSuperview];
}


#pragma mark - private methods
- (void)actionAlert:(NSString *)msg withCode:(NSString *)code{
    [self.view endEditing:YES];
    if ([code intValue ]== 0) {
        msg = @"操作成功";
    }
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示!" message:msg preferredStyle:UIAlertControllerStyleAlert];
    
    [self presentViewController:alertC animated:YES completion:^{
        NSLog(@"页面跳转完成");
    }];
    
    //添加一个确定按钮
    UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        if ([code intValue ]== 0) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            return ;
        
        }
        
        
    }];
    //添加提示按钮
    [alertC addAction:alertA];
}

- (void)configurationSubView:(int)type{
    
    
    _type = type;
    
    //将pickerView 添加到 backView上
    if (!_backView) {
        
        _backView=[[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight-310+44, kScreenWidth,197)];
        _pickview=[[UIPickerView alloc] initWithFrame:CGRectMake(0,30, kScreenWidth,167)];
    }
    _backView.backgroundColor = UIColorFromRGB(0xdbdbdb);
    if (kScreenWidth == 320) {
        _backView.frame = CGRectMake(0, kScreenHeight-290+44, kScreenWidth,170);
        _pickview.frame = CGRectMake(0,30, kScreenWidth,147);
    }
    _pickview.backgroundColor = [UIColor whiteColor];
    _pickview.delegate=self;
    _pickview.dataSource = self;
    [self.view addSubview:_backView];
    [_backView addSubview:_pickview];
    [self creatButton];
    
    
}


-(void)creatButton{
    //取消按钮
    UIButton *leftBtn=[UIButton buttonWithType:UIButtonTypeSystem];
    leftBtn.frame=CGRectMake(20,6,50,20);
    leftBtn.titleLabel.font=[UIFont systemFontOfSize:16];
    [leftBtn setTitleColor: UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    [leftBtn setTitle:@"取消" forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_backView addSubview:leftBtn];
    //确定按钮
    UIButton *rightBtn=[UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.tag = 10086;
    rightBtn.frame=CGRectMake(kScreenWidth-70,6,50,20);
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:16];
    [rightBtn setTitleColor:  UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(okBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_backView addSubview:rightBtn];
}



- (BOOL)isCanUpData{
    
    //姓名
    if ([self.tfdWorkerName.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示" message:@"姓名不能为空!" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return NO;
    }
    
    
    //id_Card
    if ([self.tfdIDnumber.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示" message:@"身份证号不能为空!" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return NO;
    }
    
    if (![self _validateIdentityCard:self.tfdIDnumber.text]) {
        [self showAlertWithTitle:@"温馨提示" message:@"身份证号格式有误!" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return NO;
    }
    
    //价格
    if ([self.tfdPrice.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示" message:@"您还没有填写价格!" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return NO;
    }
    if (self.tfdPrice.text.integerValue<=0 || self.tfdPrice.text.integerValue>1000) {
        [self showAlertWithTitle:@"温馨提示" message:@"价格只能位于1-1000之间!" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return NO;
    }

    
    
    
    
    
    //工种
    if ([self.workType.titleLabel.text isEqualToString:@"工种类型"] || [self.workType.titleLabel.text isEqualToString:@"点击选择工种"] ) {
        [self showAlertWithTitle:@"温馨提示" message:@"您还没有选择工种!" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return NO;
    }
    
    //入行年份
    if ([self.startTime.titleLabel.text isEqualToString:@"点击选择入行年份"]) {
        [self showAlertWithTitle:@"温馨提示" message:@"您还没有选择工龄!" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return NO;
    }
    
    //图片选择
    if (!_picIsfinishPick) {
        [self showAlertWithTitle:@"温馨提示" message:@"您的图片信息还没有提交完整" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return NO;
    }
    return YES;
}



//身份证号
-(BOOL) _validateIdentityCard: (NSString *)identityCard {
    
    
    if(identityCard.length!= 18){
        return NO;
    }
    
    NSString *id_17 = [identityCard substringToIndex:17];
    NSRange range = NSMakeRange(17, 1);
    NSString *id_last = [identityCard substringWithRange:range];
    NSLog(@"last:%@", id_last);
    
    //加权因子
    NSArray *factor = [NSArray arrayWithObjects:@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2", nil];
    
    //校验码对应值
    NSArray *verify_number_list = [NSArray arrayWithObjects:@"1", @"0", @"X", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2", nil];
    
    NSInteger checksum = 0;
    for (int i = 0; i < id_17.length; i++) {
        NSRange range = NSMakeRange(i, 1);
        NSString *fac = [factor objectAtIndex:i];
        checksum += [id_17 substringWithRange:range].intValue *fac.intValue;
    }
    
    int mod = checksum % 11;
    NSString *verify_number = [verify_number_list objectAtIndex:mod];
    NSLog(@"校验值%@", verify_number);
    if ([verify_number isEqualToString:id_last]) {
        return YES;
    } else {
        return NO;
    }
    
}

-(void)endselectedPhtotos{



    if (_iconType == 0) {
        
        _iconImage = _selectedPhotos[0];
        [_btnIcon setBackgroundImage:_iconImage forState:UIControlStateNormal];
        
        
        
        
    }else{
        
        _idCardImage =_selectedPhotos[0];
        
        [_btnIDnumber setBackgroundImage:_idCardImage forState:UIControlStateNormal];
        
        
    }
    
    

//图片选择完毕可以上传图片了

if (_idCardImage &&_iconImage) {
    _picIsfinishPick = YES;
}



}

#pragma mark - gettsers and setters
-(UILabel *)lblWorkerName{
    
    if (!_lblWorkerName) {
        _lblWorkerName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
        _lblWorkerName.text = @"姓名:";
        _lblWorkerName.font = [UIFont systemFontOfSize:13];
    }
    return _lblWorkerName;
}

-(UILabel *)lblProfession{
    
    if (!_lblProfession) {
        _lblProfession = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
        _lblProfession.text = @"工种:";
        _lblProfession.font = [UIFont systemFontOfSize:13];
    }
    return _lblProfession;
}

-(UILabel *)lblIDnumber{
    
    if (!_lblIDnumber) {
        _lblIDnumber = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 20)];
        _lblIDnumber.text = @"身份证号:";
        _lblIDnumber.font = [UIFont systemFontOfSize:13];
    }
    return _lblIDnumber;
}

-(UILabel *)lblStartTime{
    
    if (!_lblStartTime) {
        _lblStartTime = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 20)];
        _lblStartTime.text = @"入行时间:";
        _lblStartTime.font = [UIFont systemFontOfSize:13];
    }
    return _lblStartTime;
}

-(UILabel *)lblPrice{
    
    if (!_lblPrice) {
        _lblPrice = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 20)];
        _lblPrice.text = @"每平方单价:";
        _lblPrice.font = [UIFont systemFontOfSize:13];
    }
    return _lblPrice;
}



- (UITapGestureRecognizer *)tap{
    if (!_tap) {
        _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapAction)];
    }
    
    return _tap;
}




@end
